package cn.com.czpb.client.module.news.fragment;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.com.czpb.client.R;
import cn.com.czpb.client.app.MyActivitymanager;
import cn.com.czpb.client.config.CODE;
import cn.com.czpb.client.custorm.RecycleViewDivider;
import cn.com.czpb.client.custorm.smartrefreshalayout.ClassHeader_other;
import cn.com.czpb.client.model.news.NewsBean;
import cn.com.czpb.client.model.news.NewsListEntity;
import cn.com.czpb.client.module.news.NewsBaseFragment;
import cn.com.czpb.client.module.news.ZixunFragment;
import cn.com.czpb.client.module.news.adapter.NewsItemListViewAdapterNew;
import cn.com.czpb.client.module.news.view.ZhengwuTopView;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.ParamUtils;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2018/5/10.
 */

public class ZhengWuFragment extends NewsBaseFragment implements BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.RequestLoadMoreListener, OnRefreshListener {
    @BindView(R.id.recyclerview_highrise)
    RecyclerView recyclerView;
    @BindView(R.id.swipe_layout)
    SmartRefreshLayout swipe_layout;
    private NewsItemListViewAdapterNew adapter;
    private List<NewsBean> list;
    private int Page = 1;
    private static final int PageSize = 15;
    private boolean mFlagRefresh = true;//刷新还是加载
    private String mTitle;

    private View headView;
    private View footView;
    int SCROLL_HIGH;
    private String currentcid;
    private ZhengwuTopView topView;

    @Override
    public int setMyContentView() {
        return R.layout.fragment_zheng_wu;
    }


    public static final ZhengWuFragment newInstance() {
        ZhengWuFragment fragment = new ZhengWuFragment();
        return fragment;
    }


    @Override
    public void initView() {

        init();
    }

    @Override
    public void initData() {
        super.initData();
    }

    public void setTitle(String title) {
        mTitle = title;
    }

    public String getTitle() {
        return mTitle;
    }

    @Override
    public void init() {
        currentcid= CODE.CID_ZIZHIQU;
        list = new ArrayList<>();
        initList(currentcid);
        adapter = new NewsItemListViewAdapterNew(activity,list,false);
        adapter.setOnItemChildClickListener(this);
        adapter.setOnLoadMoreListener(this,recyclerView);
        GridLayoutManager manager = new GridLayoutManager(activity, 1);
        recyclerView.setLayoutManager(manager);
        addHeaderView();
//        addFootView();

        recyclerView.setAdapter(adapter);
        int height = (int) getResources().getDimension(R.dimen.x2);
        recyclerView.addItemDecoration(new RecycleViewDivider(activity,
                LinearLayoutManager.HORIZONTAL, height,
                getResources().getColor(R.color.color_e8e8e8)));
        swipe_layout.setRefreshHeader(new ClassHeader_other(activity));

        swipe_layout.setOnRefreshListener(this);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                // 当停止滑动时
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //获取最后一个完全显示的ItemPosition ,角标值
                    //获取 第一个条目
                    int firstItem = manager.findFirstCompletelyVisibleItemPosition();
                    LogUtils.i("firstitem-->"+firstItem);
                    if (firstItem ==0){
                        ((ZixunFragment)ZhengWuFragment.this.getParentFragment()).toVisbility();
                    }
                    //所有条目,数量值
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                LogUtils.e("scroll--" + dx + "--" + dy + "---" + SCROLL_HIGH);
                SCROLL_HIGH-=dy;
            }
        });
    }

    private void initList(String cid) {
        Map<String, String> map = new HashMap<>();
        map.put("cid",cid);
        map.put("Page", Page + "");
        map.put("PageSize", PageSize + "");
        Factory.provideHttpService().govermentlist(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsListEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsListEntity collectEntity) {
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsListEntity>() {
                    @Override
                    public void call(NewsListEntity entity) {

                        LogUtils.e("code--" + entity.code);
                        if (mFlagRefresh) {
                            swipe_layout.finishRefresh();

                        }
                        if ("200".equals(entity.code)) {
                            setListData(entity.data);
                            if (mFlagRefresh) {
                                LogUtils.i("200-->saveAll");
                                DataSupport.deleteAll(NewsBean.class);
                                DataSupport.saveAll(entity.data);
                            }

                        } else if ("209".equals(entity.code)) {

                            list.clear();
                            adapter.notifyDataSetChanged();
                        } else {
                            if (!mFlagRefresh) {
                                Page--;
                            }
                        }
                        mFlagRefresh = false;
                    }

                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("throwable--" + throwable.getMessage());
                    }
                });


    }

    public void setListData(List<NewsBean> list) {
        if (mFlagRefresh) {
            adapter.setNewData(list);
            adapter.notifyDataSetChanged();
        } else {
            adapter.addData(list);
            adapter.notifyDataSetChanged();
            adapter.loadMoreComplete();
        }
        LogUtils.i("size-->" + adapter.getData().size());
        if (list.size() < PageSize) {
            //关闭刷新
            adapter.loadMoreEnd(true);
        }
    }

    private void addHeaderView() {
        topView = ZhengwuTopView.instance(activity);
        topView.setRefreshListener(new ZhengwuTopView.RefreshListener() {
            @Override
            public void refreshData(String code) {
                currentcid= code;
                Page = 1;
                mFlagRefresh = true;
                swipe_layout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipe_layout.finishRefresh();
                    }
                },3000);
                initList(currentcid);
            }
        });
        adapter.addHeaderView(topView.getView());

    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        final NewsBean newsBean = (NewsBean) adapter.getItem(position);
        switch (view.getId()) {
            case R.id.newsItem_root:
                ////REFACTOR: 2017/8/18 添加浏览量bug
//                addCount(newsBean);
                MyActivitymanager.pushActivity(activity, newsBean, newsBean.getTid(), "newsitem", newsBean.getRvalue());
                LogUtils.e("rtype--" + newsBean.getRtype());
                break;
        }
    }

    @Override
    public void onLoadMoreRequested() {
        mFlagRefresh = false;
        Page++;
        initList(currentcid);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        Page = 1;
        mFlagRefresh = true;
        swipe_layout.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipe_layout.finishRefresh();
            }
        },3000);
        initList(currentcid);
    }
}
